<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="icon iconfont icon-jifen"></i>商城轮播图管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">

            <el-button type="primary" @click="add">新增商城轮播图</el-button>

            </div>
            <el-table :data="tableData" border style="width: 100%" >
                <el-table-column prop="id" label="ID" width="80" align="center">
                </el-table-column>
                <el-table-column  label="轮播图" align="center">
                    <template slot-scope="scope">
                        <div style="width:300px;height:100px;" >
                            <img :src="scope.row.img" style="width:300px;height:100px;"/>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="url" label="链接ID" width="200" align="center">
                </el-table-column>
                <!-- <el-table-column prop="url" label="跳转链接" width="200" align="center">
                </el-table-column> -->
                <el-table-column prop="create_time" label="创建时间" width="200" align="center">
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button size="small" type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="small" type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination" v-show="totalPages>10">
                <el-pagination @current-change="handleCurrentChange" layout="prev, pager, next" :total="totalPages">
                </el-pagination>
            </div>
        </div>
        <!-- 编辑弹出框 -->
        <el-dialog :title="dialogText" :visible.sync="editVisible" width="800px" :before-close="closeDialog">
            <el-form ref="form"  label-width="80px">
                <el-form-item label="轮播图：">
                    <div class="sola-upload clearfix" >
                        <div class="sola-left " v-show="uploadImg"><img :src="uploadImg" /></div>
                        <div class="sola-upload-right">
                            <el-upload v-show = "showAdd"
                            class="avatar-uploader"
                            :action="action"
                            :show-file-list="false"
                            :http-request="myUpload"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </div>
                        <span style="color:red;">每张图片控制在1MB以下</span>
                    </div>
                </el-form-item>
                <el-form-item label="跳转分类">
                 <el-select v-model="form.classify"  @change="changeType" placeholder="请选择跳转分类">
                    <el-option label="无链接" value="0"></el-option>
                    <el-option label="商品" value="1"></el-option>
                    <el-option label="普通项目" value="2"></el-option>
                    <el-option label="拼团项目" value="3"></el-option>
                  
                 </el-select>
               </el-form-item>
               <el-form-item label="跳转ID" v-show="form.classify!=0">
                <el-input v-model="form.id" placeholder="请输入跳转ID" style="width: 200px"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="400px" center >
            <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="deleteRow">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name:"member",
    data () {
        return {
            accept: 'image/gif, image/jpeg, image/png, image/jpg', //图片上传类型
            pageIndex:1,//当前页码
            pageSize:10,//每页10条
            totalPages:1,//默认的总条数
            title:'',// 新闻标题
            tableData:[],//表格数据
            delVisible:false, //删除确认提示，默认隐藏
            delIndex:0,
            delId:0,
            dialogText:'新增轮播图',
            editVisible:false,//编辑框默认隐藏
            editVisibleIdx:-1,//默认是新增 ID为零
            form:{
              classify: '',
              id:'',
            },
            action:"http://localhost:8080/api/common/upload/base64",// Element默认上传的接口地址
            uploadImg:'',//存放图片地址
            uploadImgFlag:false ,//图片上传之后是否显示
            showAdd:true // 图片上传按钮是否显示

        }
    },
    mounted () {
        //console.log("初始化加载了");
        this.getMemberData();
    },
    watch :{
        countTime: function(val){

        }
    },
    methods: {
        //获取tabs数据
        getMemberData (){
            let _this =this;
            this.$axios.get('/manage/index/banner/list', {
                params: {
                  type: 2
                }
            })
            .then(function (response) {
                // console.log(response);
                if(response.data.code==200){
                    //console.log(response.data.data);
                    // console.log(_this.tableData);
                    _this.tableData = response.data.data;//赋值 table 列表数据
                    //this.totalPages = response.data.data.totalPages;//更新分页总条数
                }else{
                    this.$notify.error({
                        title: '获取新闻列表失败',
                        duration:2000,
                        message: '失败原因：'+response.data.msg
                    });
                }
            })
            .catch(function (response) {
                console.log(response);
            });

        },
        // 分页导航
        handleCurrentChange (val){
            // this.cur_page = val;
            //     this.getData();
        },
        closeDialog (){
            //alert("关闭了");
            this.form.id = '',
            this.form.classify = '',
            this.showAdd = true,

            this.uploadImg ="";//保存编辑状态时候的 图片地址
            this.uploadImgFlag = false;//保存编辑状态时候的 显示图片地址
            this.editVisible = false;
        },
          //触发项目类型
        changeType(event){
            // console.log(event);
            if(event==0){
                //当选择无链接时，清空id
                this.form.id = '';
            }
        },
        //新增轮播图
        add (){
            this.editVisibleIdx =-1;
            this.editVisible = true;
            this.dialogText ="新增商城轮播图";
        },
        //编辑
        handleEdit (index,row){
            // console.log(row);
            if(row.id && row.id>0){
                this.editVisibleIdx =parseInt(row.id); //保存编辑ID
                this.uploadImg =row.img;//保存编辑状态时候的 图片地址
                this.uploadImgFlag = true;//保存编辑状态时候的 显示图片地址
                
                this.form.id = row.url;
                this.dialogText ="编辑商城轮播图";
                this.editVisible = true;
                // console.log(row.url_type);
                if(row.url_type == 1){
                    this.form.classify = '1';
                }else if(row.url_type == 2){
                    this.form.classify = '2';
                }else if(row.url_type == 3){
                    this.form.classify = '3';
                }else{
                    this.form.classify = '0';
                }
            }
        },
        //保存新增或者编辑
                saveEdit (){
            let _this = this;
            // console.log(this.editVisibleIdx);
            if(this.editVisibleIdx == -1){
                //新增
                // console.log("新增");
                var api = '/manage/index/banner/add';
            }else{
                //编辑
                // console.log("编辑");
                var  api = '/manage/index/banner/update';
            }

           
            if(this.uploadImg==""){
                this.$message.error('请先上传图片');
                return false;
            }else if(this.form.classify == ''){
                this.$message.error('请选择跳转分类');
                return false;
            }else{
                
                const param = {
                    id: this.editVisibleIdx,
                    type: 2,//商城轮播图
                    img:this.uploadImg,
                    urlType:this.form.classify,
                    url:this.form.id
                }

                // console.log(param);
                const querystring = require('querystring')

                this.$axios.post(api,querystring.stringify(param)).then(response=>{
                    //console.log(response);
                    if(response.data.code==200){
                        this.$message({
                            message: '恭喜你，操作成功',
                            type: 'success'
                        });
                        setTimeout(function(){
                            _this.uploadImg ="";
                            _this.form.id = '',
                            _this.form.classify = '',
                            _this.showAdd = true,
                            _this.uploadImgFlag =  false,
                            _this.editVisible = false;
                            _this.getMemberData(); //刷新表格
                        },1500);

                    }else{
                        this.$notify.error({
                            title: '操纵失败',
                            duration:2000,
                            message: '失败原因：'+response.data.msg
                        });
                    }

                }).catch(error=>{
                    console.log(error);
                });
            }

        },
        //删除
        handleDelete (index,row){
            if(row.id && row.id>0){
                this.delVisible = true;
                this.delIndex = index;//当前要删除的下标
                this.delId = row.id;// 当前选中ID
            }
        },
        deleteRow (){
            //console.log("触发了确定");
            if(this.delId>0){
                const querystring = require('querystring');
                const param ={
                    id:this.delId
                }
                this.$axios.post('/manage/index/banner/delete',querystring.stringify(param)).then(response=>{
                    //console.log(response);
                    if(response.data.code==200){
                        this.tableData.splice(this.delIndex, 1);
                        this.$message.success('删除成功');
                        this.delVisible = false;
                    }else{
                        this.$notify.error({
                            title: '删除失败',
                            duration:2000,
                            message: '失败原因：'+response.data.msg
                        });
                    }

                }).catch(error=>{
                    console.log(error);
                });
            }
        },
        //上传图片
        myUpload (content){
            let _this=this;
            if (typeof(FileReader) === 'undefined') {
                this.$notify.error({
                    title: '错误',
                    message: '抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！'
                });

            } else {
                let file =content.file;
                //console.log(file);
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function(e) {
                    var base = this.result;
                    //console.log(base);
                    _this.submitElementUpload(base,content);
                }
            }

        },
        //拿到base 图片之后，axios提交图片上传
        submitElementUpload (base,content){
            const querystring = require('querystring');
            const param ={
                base64:base
            }
            this.$axios.post('/api/common/upload/base64',querystring.stringify(param)).then(response=>{
                //console.log(response);
                if(response.data.code==200){
                    this.$message({
                        message: '恭喜你，图片上传成功',
                        type: 'success'
                    });
                    this.showAdd = false
                    this.uploadImg=response.data.data;//单张图片
                    this.uploadImgFlag = true;
                    content.file = null; //清空对象
                }else{
                    this.$notify.error({
                        title: '上传图片失败',
                        duration:2000,
                        message: '失败原因：'+response.data.msg
                    });
                }

            }).catch(error=>{
                console.log(error);
            });
        },
        //上传失败
        handleAvatarError(res){
            //console.log(res);
        },
        //上传成功
        handleAvatarSuccess(res, file) {
            //console.log("上传成功");
            //this.imageUrl = URL.createObjectURL(file.raw);
        },
        //
        beforeAvatarUpload(file) {
             const type = file.type;
            const isLt2M = file.size / 1024 / 1024 < 1;

            if(this.accept.indexOf(type) == -1){  
                this.$message.error('请选择gif,jpeg,png,jpg格式图片上传！');
                return false;
            }  
            if (!isLt2M) {
                this.$message.error('上传的图片大小不能超过 1MB!');
                return false;
            }
            // return isJPG && isLt2M;
            return type && isLt2M;
        }

    }
}
</script>
<style lang="stylus" scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
        margin-right :30px;
    }
    .del-dialog-cnt{
        font-size: 16px;
        text-align: center
    }
    /*上传图片*/
    .sola-upload{
        .sola-left{
            float:left
            width: 360px;
            height: 180px;
            margin-bottom 20px;
            margin-right:15px;
            img {
                width :100%;
                height :100%;
            }
        }
        .sola-upload-right{
            float:left;
            position relative;
            margin-bottom 20px;
        }

    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
